home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7431 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  68 lines

  1. Path: news.bridge.net!news
  2. From: David Byrden <100101.2547@compuserve.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: STL
  5. Date: 23 Feb 1996 08:49:06 GMT
  6. Organization: self-employed
  7. Message-ID: <4gjv22$4i1@news.bridge.net>
  8. References: <4gdgt0$494@netaxs.com>
  9. NNTP-Posting-Host: ppp-mia1-63.bridge.net
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 1.1N (Windows; I; 16bit)
  14.  
  15.  
  16. >>>
  17. class myclass
  18. {
  19.   int myint;
  20.   float myfloat;
  21.  
  22. };
  23. >>>
  24.  
  25. >> I want use "list" and stuff a bunch of these in using push_back.  No
  26. >> problem so far.  But I want the user to be able to select which item 
  27. >> to sort on... myint or myfloat
  28.  
  29.  
  30.   Whose compiler and whose STL are you using? The List class is supposed 
  31. to have a sort member function which is templated. HP's STL does not 
  32. provide it because few compilers can support template member functions 
  33. (if any?)
  34.  
  35.  
  36.   You need to use a container where you can do sorts with a templated 
  37. functor. The sort algorithm itself has a suitable version but it requires 
  38. random access iterators, so that rules out "list".
  39.  
  40.  
  41.   Once you can sort with a templated functor, you need to write a couple 
  42. of functors to go with your class, one of which compares the objects' 
  43. ints, and the other of which compares their floats. These functors don't 
  44. need any data attached, so they can be functions.
  45.  
  46.  
  47.   Here we go;
  48.  
  49.  
  50. inline bool intCompare( const myclass& lhs, const myclass& rhs )
  51. {
  52.     return  lhs.myint < rhs.myint ;
  53. }
  54.  
  55.  
  56. vector< myclass >  myThings;
  57.  
  58. sort( myThings.begin(), myThings,end(), intCompare ) ;
  59.  
  60.  
  61. See?
  62.  
  63.  
  64.                     David
  65.  
  66.  
  67.  
  68.